package com.nhvu.compoundword;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.nhvu.compoundword.base.CompoundWord;
import com.nhvu.compoundword.base.CompoundWordManager;
import com.nhvu.compoundword.library.Common;
import com.nhvu.compoundword.library.CommonSingle;
import com.nhvu.compoundword.library.MyGlobal;
import com.startapp.android.publish.StartAppSDK;

/**
 * @author Administrator
 * 
 */
public class SinglePlayerActivity extends ActionBarActivity {
	List<String> listWord = new ArrayList<String>();
	List<Integer> listPoint = CommonSingle.getListPoint();
	List<CompoundWord> compoundWords;
	CompoundWordManager manager;
	ProgressBar progressBar;
	Button btnCellStart;
	Button btnCellEnd;
	int currentIndex = 0;
	int clickCounter = 0;
	int currentPoint = 0;
	int currentMission = 0;
	int levelPoint;
	TextView tvwTimer;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Init StartApp
		StartAppSDK.init(this, MyGlobal.StartApp.DEV_ID,
				MyGlobal.StartApp.APP_ID, true);
		// Set full screen
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_single_player);
		manager = new CompoundWordManager(this);
		initData();
		displayInfo();
		displayTimer();
	}

	@Override
	public void onBackPressed() {
		Intent intent = new Intent(this, MainActivity.class);
		startActivity(intent);
		Common.closeApp(this);
	}

	/**
	 * Init list of words
	 */
	public void initData() {
		compoundWords = manager.getListImportantWordSingle();
		if (compoundWords == null
				|| compoundWords.size() < MyGlobal.SinglePlayerValues.TOTAL_WORD)
			compoundWords = manager.getListNoneImportantWordSingle();
		if (compoundWords == null
				|| compoundWords.size() < MyGlobal.SinglePlayerValues.TOTAL_WORD) {
			manager.updateUsedState(MyGlobal.TableName.SINGLE_PLAYER);
			compoundWords = manager.getListImportantWordSingle();
		}
		for (CompoundWord word : compoundWords) {
			String[] words = word.Words.split(" ");
			listWord.add(words[0]);
			listWord.add(words[1]);
		}
		Collections.shuffle(listWord);
		Collections.shuffle(listPoint);
		setData();
	}

	/**
	 * Display point bar
	 */
	public void displayInfo() {
		currentMission = CommonSingle.getCurrentMission(this);
		currentPoint = CommonSingle.getCurrentPoint(this);
		levelPoint = CommonSingle.getPointLevel(currentMission);
		if (currentPoint > levelPoint)
			currentPoint = currentPoint - levelPoint;
		else
			currentPoint = 0;
		TextView tvwMission = (TextView) findViewById(R.id.tvwMission);
		tvwMission.setText(String.valueOf(currentMission));

		TextView tvwPoint = (TextView) findViewById(R.id.tvwPoint);
		String pointFormat = String.valueOf(currentPoint)
				+ MyGlobal.FormatSign.OVER + String.valueOf(levelPoint);
		tvwPoint.setText(pointFormat);

		progressBar = (ProgressBar) findViewById(R.id.progressbar);
		progressBar.setProgress(currentPoint);
		progressBar.setMax(levelPoint);
	}

	/**
	 * Set data
	 */
	public void setData() {
		ViewGroup groupFrame = (ViewGroup) findViewById(R.id.layoutFrame);
		for (int i = 0; i < groupFrame.getChildCount(); i++) {
			View childView = groupFrame.getChildAt(i);
			ViewGroup viewGroup = (ViewGroup) childView;
			setTextToButton(viewGroup);
		}
	}

	/**
	 * Set text to button
	 * 
	 * @param group
	 *            a ViewGroup
	 */
	public void setTextToButton(ViewGroup group) {
		for (int i = 0; i < group.getChildCount(); i++) {
			View childView = group.getChildAt(i);
			if (childView instanceof Button) {
				Button btnCell = (Button) childView;
				btnCell.setText(listWord.get(currentIndex).toString());
				switch (listPoint.get(currentIndex)) {
				case MyGlobal.SinglePlayerValues.KIND_POINT_ONE:
					btnCell.setBackgroundResource(R.drawable.bg_cell_10);
					btnCell.setTag(MyGlobal.SinglePlayerValues.KIND_POINT_ONE);
					break;
				case MyGlobal.SinglePlayerValues.KIND_POINT_TWO:
					btnCell.setBackgroundResource(R.drawable.bg_cell_20);
					btnCell.setTag(MyGlobal.SinglePlayerValues.KIND_POINT_TWO);
					break;
				case MyGlobal.SinglePlayerValues.KIND_POINT_THREE:
					btnCell.setBackgroundResource(R.drawable.bg_cell_30);
					btnCell.setTag(MyGlobal.SinglePlayerValues.KIND_POINT_THREE);
					break;
				default:
					btnCell.setBackgroundResource(R.drawable.bg_cell_50);
					btnCell.setTag(MyGlobal.SinglePlayerValues.KIND_POINT_FOUR);
					break;
				}
				currentIndex++;
				// childView.setOnClickListener(onClickListener);
			}
		}
	}

	public void showMessage(String message) {
		final Toast toast = Toast.makeText(getApplicationContext(), message,
				Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
		toast.show();
		Handler handler = new Handler();
		handler.postDelayed(new Runnable() {
			@Override
			public void run() {
				toast.cancel();
			}
		}, 1000);
	}

	public OnClickListener onClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
		}
	};

	/**
	 * Highlight cell and check meaning as player clicked
	 */
	public void hightLight(View view) {
		if (clickCounter == 0) {
			if (btnCellStart != null && btnCellEnd != null) {
				Common.setBackgroundOriginal(btnCellStart);
				Common.setBackgroundOriginal(btnCellEnd);
			}
			btnCellStart = (Button) view;
			Common.setBackgroundClicked(btnCellStart);
			clickCounter++;
			return;
		}
		if (clickCounter == 1) {
			clickCounter = 0;
			btnCellEnd = (Button) view;
			if (btnCellEnd == btnCellStart) {
				Common.setBackgroundOriginal(btnCellEnd);
				return;
			} else {
				Common.setBackgroundClicked(btnCellEnd);
			}
		}
		// Check word exist
		String compoundWord = btnCellStart.getText().toString()
				+ btnCellEnd.getText().toString();
		Boolean isExist = manager.checkWordExistByWord(compoundWord);
		if (isExist) {
			btnCellStart.setVisibility(View.INVISIBLE);
			btnCellEnd.setVisibility(View.INVISIBLE);
			int point = Common.getPoint(btnCellStart, btnCellEnd);
			currentPoint += Common.getPoint(btnCellStart, btnCellEnd);

			TextView tvwPoint = (TextView) findViewById(R.id.tvwPoint);
			String pointFormat = String.valueOf(currentPoint)
					+ MyGlobal.FormatSign.OVER + String.valueOf(levelPoint);
			tvwPoint.setText(pointFormat);

			progressBar.setProgress(currentPoint);
			showMessage("+" + point);
		} else {
			Common.setBackgroundWrong(btnCellStart);
			Common.setBackgroundWrong(btnCellEnd);
		}
	}

	/**
	 * Display timer
	 * 
	 */
	public void displayTimer() {
		int totalTime = CommonSingle.getTimeLevel(currentMission);
		int downTime = MyGlobal.SinglePlayerValues.TIME_DOWN;
		tvwTimer = (TextView) findViewById(R.id.tvwTimer);
		CountDownTimer myCountDownTimer = new CountDownTimer(totalTime,
				downTime) {
			@Override
			public void onTick(long millisUntilFinished) {
				tvwTimer.setText(String.valueOf(millisUntilFinished / 1000));
			}

			@Override
			public void onFinish() {
				tvwTimer.setText("0");
				int levelPoint = CommonSingle.getPointLevel(currentMission);
				if (currentPoint >= levelPoint) {
					showMissionComplete();
				} else {
					showMissionFail();
				}
			}
		};
		myCountDownTimer.start();
	}

	/**
	 * Go to mission complete activity
	 */
	public void showMissionComplete() {
		manager.updateUsedState(compoundWords, MyGlobal.TableName.SINGLE_PLAYER);
		CommonSingle.setCurrentPoint(this, currentPoint);
		CommonSingle.setCurrentMission(this, currentMission + 1);
		Intent intent = new Intent(this, MissionCompleteActivity.class);
		startActivity(intent);
		Common.closeApp(this);
	}

	/**
	 * Go to mission fail activity
	 */
	public void showMissionFail() {
		CommonSingle.setCurrentPoint(this, 0);
		Intent intent = new Intent(this, MissionFailActivity.class);
		startActivity(intent);
		Common.closeApp(this);
	}

	public void playNextMission(View view) {
		int levelPoint = CommonSingle.getPointLevel(currentMission);
		if (currentPoint >= levelPoint) {
			showMissionComplete();
		} else {
			showMessage();
			return;
		}
	}

	public void showMessage() {
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
		alertDialogBuilder.setTitle(
				getResources().getString(R.string.message_title))
				.setNegativeButton(
						getResources().getString(
								R.string.message_not_enough_point_button),
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
		;
		// set dialog message
		alertDialogBuilder.setMessage(getResources().getString(
				R.string.message_not_enough_point));
		AlertDialog alertDialog = alertDialogBuilder.create();
		alertDialog.show();
	}
}
